package com.ydlclass.utils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * 网络工具
 * @author it楠老师
 * @createTime 2023-03-18
 */
public class NetWorkUtils {

    /**
     * 获取本地网卡的ip地址,InetAddress.getLocalHost()方法不全
     * @return ipaddress
     */
    public static String getIp() throws SocketException {
        String ip = null;
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface ni = networkInterfaces.nextElement();
            Enumeration<InetAddress> nias = ni.getInetAddresses();
            while (nias.hasMoreElements()) {
                InetAddress ia = nias.nextElement();
                if (!ia.isLinkLocalAddress() && !ia.isLoopbackAddress() && ia instanceof Inet4Address &&
                        !ia.getHostAddress().endsWith("1") && !ia.getHostAddress().endsWith("0")
                ) {
                    ip = ia.getHostAddress();
                }
            }
        }
        return ip;
    }

}
